package com.xxx.rpc.registry.redis;

import com.xxx.rpc.registry.ServiceDiscovery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

/**
 * 基于 redis 的服务发现接口实现
 * @Author: jc.huang
 * @Date: 2021/12/8
 */
public class RedisServiceDiscovery implements ServiceDiscovery {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisServiceDiscovery.class);

    private Jedis jedis;

    /**
     * 在构造时就要注入 redis 的地址
     * @param redisAddress
     */
    public RedisServiceDiscovery(String redisAddress) {
        //解析 ip 和 port
        String[] ipport = redisAddress.split(":");
        String ip = ipport[0];
        String port = ipport[1];

        jedis = new Jedis(ip, Integer.parseInt(port));
        LOGGER.debug("connect redis");
    }

    @Override
    public String discover(String serviceName) {
        String key = Constant.PREFIX + serviceName;
        String data = jedis.get(key);
        LOGGER.debug("get data from redis, key = {}, value = {}", key, data);
        return data;
    }
}
